package com.lee.service;

import com.lee.domain.Department;
import com.lee.repository.DepartmentRepository;
import com.lee.vo.EmployeeAuthInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Optional;

/**
 * @author Lee HN
 * @date 2019/7/1 14:49
 */
@Component
public class PermissionEvaluatorImpl implements PermissionEvaluator {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        Object principal = authentication.getPrincipal();
        EmployeeAuthInfo authInfo;
        if (principal instanceof EmployeeAuthInfo) authInfo = (EmployeeAuthInfo) principal;
        else return false;
        switch (String.valueOf(targetDomainObject)) {
            case "department": {
                String deptName = String.valueOf(permission);
                Optional<Department> departmentOP = departmentRepository.findByName(deptName);
                return departmentOP.map(d -> StringUtils.startsWith(authInfo.getDeptPath(), d.getRootPath())).orElse(false);
            }
            default:
                return false;
        }
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
